package com.wangshb.upms.service.impl;

import com.wangshb.upms.core.utils.AssertUtil;
import com.wangshb.upms.entity.UpmsUser;
import com.wangshb.upms.mapper.UpmsUserMapper;
import com.wangshb.upms.service.UpmsUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Set;

@Service
@Slf4j
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UpmsUserService upmsUserService;



    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        // 获取用户信息
        UpmsUser upmsUser = upmsUserService.findOne(UpmsUser.builder().userAccount(s).build());
        if (null == upmsUser) {
            throw new UsernameNotFoundException("用户名不存在");
        }

        // 获取用户对应的角色
        Set<String> roles = this.upmsUserService.findRoles(upmsUser.getUserAccount());
        if (roles == null || roles.size() == 0) {
            log.info("当前用户没有任何权限功能");
            return new User(upmsUser.getUserAccount(), upmsUser.getPassword(), CollectionUtils.emptyCollection());
        }

        ArrayList<SimpleGrantedAuthority> simpleGrantedAuthorities = new ArrayList<>(roles.size());
        roles.stream().filter(role -> null != role && role.trim().length() > 0).forEach(role -> simpleGrantedAuthorities.add(new SimpleGrantedAuthority(role)));
        return new User(upmsUser.getUserAccount(), upmsUser.getPassword(), simpleGrantedAuthorities);
    }

}
